import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // API URL
  // baseURL: '/api',
  // baseURL: '/apiTest',
  baseURL: 'http://49.235.99.41',
  // baseURL: 'http://localhost:8080'

  // 关闭浏览器缓存
  // cache: false,
  // 超时时间
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // do something before request is sent
  // 设置token头
  if (store.getters.token) {
    config.headers['token'] = getToken()
  }
  return config
},
error => {
  // 处理请求错误
  console.error(error)
  return Promise.reject(error)
}
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 响应状态管理
    if (response.code === 400 || response.code === 403 || response.code === 500) {
      return Promise.reject(Message({
        message: `服务器错误：${response.code}` || 'Error',
        type: 'warning'
      }))
    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    switch (res.status) {
      case 200:
        if (/^注意/.exec(res.msg)) {
          Message({
            message: res.msg,
            type: 'warning'
          })
        }
        return response
      case 400:
        Message({
          message: res.msg,
          type: 'warning'
        })
        return
      case 403:
        Message({
          message: res.msg,
          type: 'warning'
        })
        return
    }
  },
  error => {
    console.error(`错误：${error.message}`) // for debug
    Message({
      message: `错误：${error.message}`,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
// 暴露实例
export default service
